package top.retain.exp6;

import androidx.appcompat.app.AppCompatActivity;

import android.media.Image;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button download;
    Button show;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        download = findViewById(R.id.btn_download);
        show = findViewById(R.id.btn_show);
        img = findViewById(R.id.img);
        download.setOnClickListener(this);
        show.setOnClickListener(this);


    }


    private void download() throws IOException {
        String url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fwallpaper%2F1305%2F17%2Fc0%2F21026807_1368771642298_800x600.jpg&refer=http%3A%2F%2Fimg.pconline.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1626398079&t=4fadc6bfbd7b115928bf262ba6c022dc";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        // 异步操作
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onResponse", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) {
                String filePath = Environment.getExternalStorageDirectory() + File.separator
                        + "Pictures" + File.separator + "images.jpg";
                if (response.body().contentLength() > 0) {
                    InputStream inputStream = response.body().byteStream();
                    File file = new File(filePath);
                    Log.d("图片地址：",file.toString());
                    // 目录存在
                    if (file.getParentFile().exists()) {
                        FileOutputStream fos = null;
                        try {
                            fos = new FileOutputStream(file);
                            int len;
                            // 写入图片
                            while (((len = inputStream.read()) != -1)) {
                                fos.write(len);
                            }
                            Looper.prepare();
                            Toast.makeText(MainActivity.this, "图片下载成功！保存在："+file.getPath(), Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            Log.d("onResponse","文件未找到！");
                        } catch (IOException e) {
                            e.printStackTrace();
                            Log.d("onResponse","操作异常！");
                        }
                    }else {
                        Looper.prepare();
                        Toast.makeText(MainActivity.this, "目录不存在，正在创建目录", Toast.LENGTH_SHORT).show();
                        Looper.prepare();
                        Log.d("onResponse","目录不存在，正在创建目录···");
                        // 否则创建目录
                        boolean res = file.getParentFile().mkdirs();
                        Log.d("onResponse","创建目录："+res);
                    }
                }else {
                    // 访问的文件不存在
                    Looper.prepare();
                    Toast.makeText(MainActivity.this, "访问的图片不存在！", Toast.LENGTH_SHORT).show();
                    Looper.prepare();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_download:
                try {
                    download();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_show:
                showImages();
        }

    }

    private void showImages() {
        String filePath = Environment.getExternalStorageDirectory() + File.separator
                + "Pictures" + File.separator + "images.jpg";
        File file=new File(filePath);
        Glide.with(MainActivity.this).load(file).into(img);
    }
}